import torch
import torch.nn as nn
import torch.nn.functional as F
import network.resnet as resnet
import torchvision.transforms as transforms
from collections import OrderedDict
from einops import rearrange
from timm.models.layers import DropPath, to_2tuple, trunc_normal_


WindowProcess = None
WindowProcessReverse = None

class RelativePositionBias(nn.Module):
    # input-independent relative position attention
    # As the number of parameters is smaller, so use 2D here
    # Borrowed some code from SwinTransformer: https://github.com/microsoft/Swin-Transformer/blob/main/models/swin_transformer.py
    def __init__(self, num_heads, h, w):
        super().__init__()
        self.num_heads = num_heads
        self.h = h
        self.w = w

        self.relative_position_bias_table = nn.Parameter(
            torch.randn((2 * h - 1) * (2 * w - 1), num_heads) * 0.02)

        coords_h = torch.arange(self.h)
        coords_w = torch.arange(self.w)
        coords = torch.stack(torch.meshgrid([coords_h, coords_w]))  # 2, h, w
        coords_flatten = torch.flatten(coords, 1)  # 2, hw

        relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]
        relative_coords = relative_coords.permute(1, 2, 0).contiguous()
        relative_coords[:, :, 0] += self.h - 1
        relative_coords[:, :, 1] += self.w - 1
        relative_coords[:, :, 0] *= 2 * self.h - 1
        relative_position_index = relative_coords.sum(-1)  # hw, hw

        self.register_buffer("relative_position_index", relative_position_index)

    def forward(self, H, W):
        relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(self.h,
                                                                                                               self.w,
                                                                                                               self.h * self.w,
                                                                                                               -1)  # h, w, hw, nH
        relative_position_bias_expand_h = torch.repeat_interleave(relative_position_bias, H // self.h, dim=0)
        relative_position_bias_expanded = torch.repeat_interleave(relative_position_bias_expand_h, W // self.w,
                                                                  dim=1)  # HW, hw, nH

        relative_position_bias_expanded = relative_position_bias_expanded.view(H * W, self.h * self.w,
                                                                               self.num_heads).permute(2, 0,
                                                                                                       1).contiguous().unsqueeze(
            0)

        return relative_position_bias_expanded
class depthwise_separable_conv(nn.Module):
    def __init__(self, in_ch, out_ch, stride=1, kernel_size=3, padding=1, bias=False):
        super().__init__()
        self.depthwise = nn.Conv2d(in_ch, in_ch, kernel_size=kernel_size, padding=padding, groups=in_ch, bias=bias, stride=stride)
        self.pointwise = nn.Conv2d(in_ch, out_ch, kernel_size=1, bias=bias)

    def forward(self, x):
        out = self.depthwise(x)
        out = self.pointwise(out)

        return out

class WindowAttention(nn.Module):
    r""" Window based multi-head self attention (W-MSA) module with relative position bias.
    It supports both of shifted and non-shifted window.

    Args:
        dim (int): Number of input channels.
        window_size (tuple[int]): The height and width of the window.
        num_heads (int): Number of attention heads.
        qkv_bias (bool, optional):  If True, add a learnable bias to query, key, value. Default: True
        qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
        attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
        proj_drop (float, optional): Dropout ratio of output. Default: 0.0
    """

    def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):

        super().__init__()
        self.dim = dim
        self.window_size = window_size  # Wh, Ww
        self.num_heads = num_heads
        head_dim = dim // num_heads
        self.scale = qk_scale or head_dim ** -0.5

        # define a parameter table of relative position bias
        self.relative_position_bias_table = nn.Parameter(
            torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads))  # 2*Wh-1 * 2*Ww-1, nH

        # get pair-wise relative position index for each token inside the window
        coords_h = torch.arange(self.window_size[0])
        coords_w = torch.arange(self.window_size[1])
        coords = torch.stack(torch.meshgrid([coords_h, coords_w]))  # 2, Wh, Ww
        coords_flatten = torch.flatten(coords, 1)  # 2, Wh*Ww
        relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]  # 2, Wh*Ww, Wh*Ww
        relative_coords = relative_coords.permute(1, 2, 0).contiguous()  # Wh*Ww, Wh*Ww, 2
        relative_coords[:, :, 0] += self.window_size[0] - 1  # shift to start from 0
        relative_coords[:, :, 1] += self.window_size[1] - 1
        relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
        relative_position_index = relative_coords.sum(-1)  # Wh*Ww, Wh*Ww
        self.register_buffer("relative_position_index", relative_position_index)

        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
        self.attn_drop = nn.Dropout(attn_drop)
        self.proj = nn.Linear(dim, dim)
        self.proj_drop = nn.Dropout(proj_drop)

        trunc_normal_(self.relative_position_bias_table, std=.02)
        self.softmax = nn.Softmax(dim=-1)

    def forward(self, x, mask=None):
        """
        Args:
            x: input features with shape of (num_windows*B, N, C)
            mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
        """
        B_, N, C = x.shape
        qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)#,B_,num_heads,N,C // self.num_heads
        q, k, v = qkv[0], qkv[1], qkv[2]  # make torchscript happy (cannot use tensor as tuple)

        q = q * self.scale

        torch.cuda.empty_cache()

        attn = (q @ k.transpose(-2, -1))#q为B_,num_heads,N,C // self.num_heads，K为#,B_,num_heads,C // self.num_heads,N

        relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
            self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1)  # Wh*Ww,Wh*Ww,nH
        relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()  # nH, Wh*Ww, Wh*Ww
        attn = attn + relative_position_bias.unsqueeze(0)

        if mask is not None:
            nW = mask.shape[0]
            attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
            attn = attn.view(-1, self.num_heads, N, N)
            attn = self.softmax(attn)
        else:
            attn = self.softmax(attn)

        attn = self.attn_drop(attn)

        x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
        x = self.proj(x)
        x = self.proj_drop(x)
        return x

    # def extra_repr(self) -> str:
    #     return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}'
    #
    # def flops(self, N):
    #     # calculate flops for 1 window with token length of N
    #     flops = 0
    #     # qkv = self.qkv(x)
    #     flops += N * self.dim * 3 * self.dim
    #     # attn = (q @ k.transpose(-2, -1))
    #     flops += self.num_heads * N * (self.dim // self.num_heads) * N
    #     #  x = (attn @ v)
    #     flops += self.num_heads * N * N * (self.dim // self.num_heads)
    #     # x = self.proj(x)
    #     flops += N * self.dim * self.dim
    #     return flops
class Mlp(nn.Module):
    def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
        super().__init__()
        out_features = out_features or in_features
        hidden_features = hidden_features or in_features
        self.fc1 = nn.Linear(in_features, hidden_features)
        self.act = act_layer()
        self.fc2 = nn.Linear(hidden_features, out_features)
        self.drop = nn.Dropout(drop)

    def forward(self, x):
        x = self.fc1(x)
        x = self.act(x)
        x = self.drop(x)
        x = self.fc2(x)
        x = self.drop(x)
        return x

class LinearAttention(nn.Module):

    def __init__(self, dim, heads=4, dim_head=64, attn_drop=0., proj_drop=0., reduce_size=16, projection='interp',
                 rel_pos=True):
        super().__init__()

        self.inner_dim = dim_head * heads
        self.heads = heads
        self.scale = dim_head ** (-0.5)
        self.dim_head = dim_head
        self.reduce_size = reduce_size
        self.projection = projection
        self.rel_pos = rel_pos

        # depthwise conv is slightly better than conv1x1
        # self.to_qkv = nn.Conv2d(dim, self.inner_dim*3, kernel_size=1, stride=1, padding=0, bias=True)
        # self.to_out = nn.Conv2d(self.inner_dim, dim, kernel_size=1, stride=1, padding=0, bias=True)

        self.to_qkv = depthwise_separable_conv(dim, self.inner_dim * 3)
        self.to_out = depthwise_separable_conv(self.inner_dim, dim)

        self.attn_drop = nn.Dropout(attn_drop)
        self.proj_drop = nn.Dropout(proj_drop)

        if self.rel_pos:
            # 2D input-independent relative position encoding is a little bit better than
            # 1D input-denpendent counterpart
            self.relative_position_encoding = RelativePositionBias(heads, reduce_size, reduce_size)
            # self.relative_position_encoding = RelativePositionEmbedding(dim_head, reduce_size)

    def forward(self, x):

        B, C, H, W = x.shape

        # B, inner_dim, H, W
        qkv = self.to_qkv(x)
        q, k, v = qkv.chunk(3, dim=1)

        if self.projection == 'interp' and H != self.reduce_size:
            k, v = map(lambda t: F.interpolate(t, size=self.reduce_size, mode='bilinear', align_corners=True), (k, v))

        elif self.projection == 'maxpool' and H != self.reduce_size:
            k, v = map(lambda t: F.adaptive_max_pool2d(t, output_size=self.reduce_size), (k, v))

        q = rearrange(q, 'b (dim_head heads) h w -> b heads (h w) dim_head', dim_head=self.dim_head, heads=self.heads,
                      h=H, w=W)
        k, v = map(lambda t: rearrange(t, 'b (dim_head heads) h w -> b heads (h w) dim_head', dim_head=self.dim_head,
                                       heads=self.heads, h=self.reduce_size, w=self.reduce_size), (k, v))

        q_k_attn = torch.einsum('bhid,bhjd->bhij', q, k)

        if self.rel_pos:
            relative_position_bias = self.relative_position_encoding(H, W)
            q_k_attn += relative_position_bias
            # rel_attn_h, rel_attn_w = self.relative_position_encoding(q, self.heads, H, W, self.dim_head)
            # q_k_attn = q_k_attn + rel_attn_h + rel_attn_w

        q_k_attn *= self.scale
        q_k_attn = F.softmax(q_k_attn, dim=-1)
        q_k_attn = self.attn_drop(q_k_attn)

        out = torch.einsum('bhij,bhjd->bhid', q_k_attn, v)
        out = rearrange(out, 'b heads (h w) dim_head -> b (dim_head heads) h w', h=H, w=W, dim_head=self.dim_head,
                        heads=self.heads)

        out = self.to_out(out)
        out = self.proj_drop(out)

        return out

class LearnedAttention(nn.Module):
    def __init__(self, HmutiW, rel_pos=True):
        super().__init__()
        self.attn=nn.Linear(HmutiW, HmutiW , bias=True)
    def forward(self, x):
        B, C, H, W = x.shape
        # B, inner_dim, H, W
        x=x.reshape(B,C,H*W)
        x=self.attn(x)
        x=x.reshape(B,C,H,W)
        return x

class WinLearnedAttention(nn.Module):
    def __init__(self, H,dim ):
        super(WinLearnedAttention, self).__init__()
        self.attn = nn.Sequential(
            nn.Linear(H*H,H* H, bias=True),
            nn.BatchNorm1d(dim),
            nn.ReLU()
        )



        # self.BN=nn.BatchNorm1d(dim)
        # self.attnH=nn.Sequential(
        #     nn.Linear(H,H, bias=True),
        #     # nn.BatchNorm2d(H),
        #     nn.ReLU(inplace=True),
        # )
        #self.norm= nn.BatchNorm2d(H)
        # self.attnChannel = nn.Sequential(
        #     nn.Conv2d(inChannel, outChannel, kernel_size=1, stride=1, padding=0, bias=True),
        #     nn.BatchNorm2d(outChannel),
        #     nn.ReLU(inplace=True),
        # )
        # self.absolute_pos_embed = nn.Parameter(torch.zeros(2, dim,H*H))
        # nn.init.trunc_normal_(self.absolute_pos_embed, std=.02)

    def forward(self, x):
        # short=x
        B, C, H, W = x.shape

        # x=self.BN(x)
        x = x.reshape(B, C, H * W)
        # x = x + self.absolute_pos_embed
        x = self.attn(x)
        x = x.reshape(B, C, H, W)
        # x=self.relu(x+short)
        return x
def learnwindow_partition(x, window_size):
    """
    Args:
        x: (B, H, W, C)
        window_size (int): window size

    Returns:
        windows: (num_windows*B, window_size, window_size, C)
    """
    B,C, H, W = x.shape
    x = x.view(B,C, H // window_size, window_size, W // window_size, window_size)
    x=x.permute(0, 2, 4, 1, 3, 5) #B, H // window_size, W // window_size,C, window_size, window_size

    windows = x.reshape(-1,C,window_size, window_size) # -1,C,winH,winW
    return windows
def window_partition(x, window_size):
    """
    Args:
        x: (B, H, W, C)
        window_size (int): window size

    Returns:
        windows: (num_windows*B, window_size, window_size, C)
    """
    B, H, W, C = x.shape
    x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
    windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
    return windows
def learnwindow_reverse(windows, H, W):
    """
    Args:
        windows: (num_windows*B, window_size, window_size, C)
        window_size (int): Window size
        H (int): Height of image
        W (int): Width of image

    Returns:
        x: (B, H, W, C)
    """
    _,C,window_size,_=windows.shape

    B = int(windows.shape[0] / (H * W / window_size / window_size))
    x = windows.view(B, H // window_size, W // window_size, C, window_size, window_size)
    x= x.permute(0,3, 1, 4, 2, 5)#B, C, H // window_size, window_size, W // window_size, window_size
    x=x.reshape(B,C,H,W)
    return x
def window_reverse(windows, window_size, H, W):
    """
    Args:
        windows: (num_windows*B, window_size, window_size, C)
        window_size (int): Window size
        H (int): Height of image
        W (int): Width of image

    Returns:
        x: (B, H, W, C)
    """
    B = int(windows.shape[0] / (H * W / window_size / window_size))
    x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
    x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
    return x

class LAttnBlock(nn.Module):
    def __init__(self, winSize,inDim=32,outDim=32):
        super(LAttnBlock, self).__init__()
        self.winAttn1 = WinLearnedAttention(winSize,inDim)
        self.winAttn2 = WinLearnedAttention(winSize,inDim)
        # self.winAttn3 = WinLearnedAttention(winSize)
        # self.winAttn4 = WinLearnedAttention(winSize),di
        self.winSize=winSize
        # self.relu = nn.ReLU(inplace=True)
        self.attnChannel1 = nn.Sequential(
            nn.Conv2d(inDim, outDim, kernel_size=1, stride=1, padding=0, bias=True),
            nn.BatchNorm2d(outDim),
            nn.ReLU(),
        )
        self.attnChannel2 = nn.Sequential(
            nn.Conv2d(outDim, outDim, kernel_size=1, stride=1, padding=0, bias=True),
            nn.BatchNorm2d(outDim),
            nn.ReLU(inplace=True),
        )
        # self.attnChannel3 = nn.Sequential(
        #     nn.Conv2d(outDim, outDim, kernel_size=1, stride=1, padding=0, bias=True),
        #     nn.BatchNorm2d(outDim),
        #     nn.ReLU(inplace=True),
        # )
        # self.attnChannel4 = nn.Sequential(
        #     nn.Conv2d(outDim, outDim, kernel_size=1, stride=1, padding=0, bias=True),
        #     nn.BatchNorm2d(outDim),
        #     nn.ReLU(inplace=True),
        # )
    def forward(self, x):
        B,C,H,W=x.shape
        short=x

        x=window_partition(x,self.winSize)#切分窗口
        x=self.winAttn1(x)#窗口化attention
        x=window_reverse(x,H,W)#拉回原始大小

        # x=F.relu(x)
        # x = self.attnChannel1(x)

        if self.winSize<=(H//2):
        # #使用pading
        #     padSize = self.winSize // 2
        #     x = F.pad(x, (padSize, padSize, padSize, padSize), "constant",0)  # 上下左右都填充winSize一半
        #     padB,padC,padH,padW=x.shape
        #     x = window_partition(x, self.winSize)  # 切分窗口
        #     x = self.winAttn2(x)  # 窗口化attention
        #     x = window_reverse(x, padH, padW)  # 拉回原始大小
        #     x = x[:, :, padSize:-padSize, padSize:-padSize]  # 切掉填充的数值
        #     #使用roll
        #     shift_size=self.winSize // 2
        #     x = torch.roll(x, shifts=(-shift_size, -shift_size), dims=(2, 3))
        #     x = window_partition(x, self.winSize)  # 切分窗口
        #     x = self.winAttn2(x)  # 窗口化attention
        #     x = window_reverse(x, H, W)  # 拉回原始大小
        #     x = torch.roll(x, shifts=(shift_size, shift_size), dims=(2, 3))
            # 使用roll
            shift_size = self.winSize // 2
            shiftL = torch.roll(x, shifts=-shift_size, dims=3)
            shiftR = torch.roll(x, shifts=shift_size, dims=3)
            shiftT = torch.roll(x, shifts=-shift_size, dims=2)
            shiftB = torch.roll(x, shifts=shift_size, dims=2)
            shiftTL = torch.roll(x, shifts=(-shift_size,-shift_size), dims=(2,3))
            shiftBR = torch.roll(x, shifts=(shift_size, shift_size), dims=(2, 3))
            x=x+shiftTL+shiftBR+shiftL+shiftR+shiftT+shiftB
            x = window_partition(x, self.winSize)  # 切分窗口
            x = self.winAttn2(x)  # 窗口化attention
            x = window_reverse(x, H, W)  # 拉回原始大小


        # x=F.relu(x+short)
        # x = window_partition(x, self.winSize)  # 切分窗口
        # x = self.winAttn3(x)  # 窗口化attention
        # x = window_reverse(x, H, W)  # 拉回原始大小

        x = self.attnChannel1(x)
        #
        # if self.winSize <= (H // 2):
        #     # 使用roll
        #     shift_size = self.winSize // 2
        #     x = torch.roll(x, shifts=(-shift_size, -shift_size), dims=(2, 3))
        #     x = window_partition(x, self.winSize)  # 切分窗口
        #     x = self.winAttn4(x)  # 窗口化attention
        #     x = window_reverse(x, H, W)  # 拉回原始大小
        #     x = torch.roll(x, shifts=(shift_size, shift_size), dims=(2, 3))

        #     # 使用shiftpooling
        #     #     x=shiftPooling(x,self.winSize)#shift pooling
        #     # x = window_partition(x, self.winSize)  # 切分窗口
        #     # x = self.winAttn1(x)  # 窗口化attention
        #     # x = window_reverse(x, H, W)  # 拉回原始大小`
        #     x = self.attnChannel4(x)

        return x
class LAttnBlock1(nn.Module):
    def __init__(self, winSize,inDim,outDim):
        super(LAttnBlock1, self).__init__()
        self.winAttn1 = WinLearnedAttention(winSize,outDim)
        self.winAttn2 = WinLearnedAttention(winSize,outDim)
        self.winSize=winSize

        self.attnChannel1 = nn.Sequential(
            nn.Conv2d(inDim, outDim, kernel_size=1, stride=1, padding=0, bias=True),
            nn.BatchNorm2d(outDim),
            nn.ReLU(),
        )
        self.attnChannel2 = nn.Sequential(
            nn.Conv2d(outDim, outDim, kernel_size=1, stride=1, padding=0, bias=True),
            nn.BatchNorm2d(outDim),
            nn.ReLU(),
        )
    def forward(self, x):
        x=self.attnChannel1 (x)

        B,C,H,W=x.shape

        x=learnwindow_partition(x,self.winSize)#切分窗口
        x=self.winAttn1(x)#窗口化attention
        x=learnwindow_reverse(x,H,W)#拉回原始大小
        if self.winSize<=(H//2):
            #使用roll

            shift_size=self.winSize // 2
            x = torch.roll(x, shifts=(-shift_size, -shift_size), dims=(2, 3))
            x = learnwindow_partition(x, self.winSize)  # 切分窗口
            x = self.winAttn2(x)  # 窗口化attention
            x = learnwindow_reverse(x, H, W)  # 拉回原始大小
            x = torch.roll(x, shifts=(shift_size, shift_size), dims=(2, 3))

        x = self.attnChannel2(x)

        return x
    #采用winsize/2的stride,winsize的maxpooling
class LAttnBlock2(nn.Module):
    def __init__(self, winSize,inDim,outDim):
        super(LAttnBlock2, self).__init__()
        self.winAttn1 = WinLearnedAttention(winSize,outDim)
        self.winAttn2 = WinLearnedAttention(winSize,outDim)
        self.winSize=winSize

        self.attnChannel1 = nn.Sequential(
            nn.Conv2d(inDim, outDim, kernel_size=1, stride=1, padding=0, bias=True),
            nn.BatchNorm2d(outDim),
            nn.ReLU(),
        )
        self.attnChannel2 = nn.Sequential(
            nn.Conv2d(outDim, outDim, kernel_size=1, stride=1, padding=0, bias=True),
            nn.BatchNorm2d(outDim),
            nn.ReLU(),
        )
    def forward(self, x):

        B,C,H,W=x.shape

        #第一次------------------------------------------
        x = self.attnChannel1(x)
        x=window_partition(x,self.winSize)#切分窗口
        x=self.winAttn1(x)#窗口化attention
        x=window_reverse(x,H,W)#拉回原始大小

        shortcut = x
        # x=F.pad(x,(4,4,4,4), mode='reflect')
        # _, _, padH, padW = x.shape
        x=F.max_pool2d(x,self.winSize,stride=4)
        x=F.interpolate(x,(H,W))+shortcut
        # x=x[:, :, 4:(H+4), 4:(W+4)]+shortcut



        #第二次------------------------
        x = self.attnChannel2(x)
        x = window_partition(x, self.winSize)  # 切分窗口
        x = self.winAttn2(x)  # 窗口化attention
        x = window_reverse(x, H, W)  # 拉回原始大小

        shortcut = x
        # x = F.pad(x, (4, 4, 4, 4), mode='reflect')
        # _, _, padH, padW = x.shape
        x = F.max_pool2d(x, self.winSize, stride=4)
        x = F.interpolate(x, (H, W))   +shortcut
        # x=x[:, :, 4:(H+4), 4:(W+4)]+shortcut


        return x
class LAttnBlock3(nn.Module):
    def __init__(self, winSize,inDim,outDim):
        super(LAttnBlock3, self).__init__()
        self.winAttn1 = WinLearnedAttention(winSize,outDim)
        self.winAttn2 = WinLearnedAttention(winSize,outDim)
        self.winSize=winSize

        self.attnChannel1 = nn.Sequential(
            nn.Conv2d(inDim, outDim, kernel_size=1, stride=1, padding=0, bias=True),
            nn.BatchNorm2d(outDim),
            nn.ReLU(),
        )
        self.attnChannel2 = nn.Sequential(
            nn.Conv2d(outDim, outDim, kernel_size=1, stride=1, padding=0, bias=True),
            nn.BatchNorm2d(outDim),
            nn.ReLU(),
        )
    def forward(self, input):

        B,C,H,W=input.shape

        x = self.attnChannel1(input)
        x=window_partition(x,self.winSize)#切分窗口
        x=self.winAttn1(x)#窗口化attention
        x=window_reverse(x,H,W)#拉回原始大小

        if self.winSize<=(H//2):
            #使用roll

            shift_size=self.winSize // 2
            shift = torch.roll(x, shifts=(-shift_size, -shift_size), dims=(2, 3))
            x=x+shift

        x = self.attnChannel2(x)
        x = window_partition(x, self.winSize)  # 切分窗口
        x = self.winAttn2(x)  # 窗口化attention
        x = window_reverse(x, H, W)  # 拉回原始大小

        if self.winSize <= (H // 2):
            # 使用roll

            shift_size = self.winSize // 2
            shift = torch.roll(x, shifts=(-shift_size, -shift_size), dims=(2, 3))
            x = x + shift


        return x
    #采用winsize/2的stride,winsize的maxpooling
class SwinTransformerBlock(nn.Module):
    r""" Swin Transformer Block.

    Args:
        dim (int): Number of input channels.
        input_resolution (tuple[int]): Input resulotion.
        num_heads (int): Number of attention heads.
        window_size (int): Window size.
        shift_size (int): Shift size for SW-MSA.
        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
        qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
        qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
        drop (float, optional): Dropout rate. Default: 0.0
        attn_drop (float, optional): Attention dropout rate. Default: 0.0
        drop_path (float, optional): Stochastic depth rate. Default: 0.0
        act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
        norm_layer (nn.Module, optional): Normalization layer.  Default: nn.LayerNorm
        fused_window_process (bool, optional): If True, use one kernel to fused window shift & window partition for acceleration, similar for the reversed part. Default: False
    """

    def __init__(self, dim, input_resolution, num_heads=2, window_size=8, shift_size=0,
                 mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
                 act_layer=nn.GELU, norm_layer=nn.LayerNorm,
                 fused_window_process=False):
        super().__init__()
        self.dim = dim
        self.input_resolution = input_resolution
        self.num_heads = num_heads
        self.window_size = window_size
        self.shift_size = shift_size
        self.mlp_ratio = mlp_ratio
        if min(self.input_resolution) <= self.window_size:
            # if window size is larger than input resolution, we don't partition windows
            self.shift_size = 0
            self.window_size = min(self.input_resolution)
        assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"

        self.norm1 = norm_layer(dim)
        '''self.attn=BuildFormer.geoseg.models.BuildFormer.LWMSA(dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
            qkv_bias=qkv_bias)
        '''
        self.attn = WindowAttention(
            dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
            qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)

        self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
        self.norm2 = norm_layer(dim)
        mlp_hidden_dim = int(dim * mlp_ratio)
        self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)

        if self.shift_size > 0:
            # calculate attention mask for SW-MSA
            H, W = self.input_resolution
            img_mask = torch.zeros((1, H, W, 1))  # 1 H W 1
            h_slices = (slice(0, -self.window_size),
                        slice(-self.window_size, -self.shift_size),
                        slice(-self.shift_size, None))
            w_slices = (slice(0, -self.window_size),
                        slice(-self.window_size, -self.shift_size),
                        slice(-self.shift_size, None))
            cnt = 0
            for h in h_slices:
                for w in w_slices:
                    img_mask[:, h, w, :] = cnt
                    cnt += 1

            mask_windows = window_partition(img_mask, self.window_size)  # nW, window_size, window_size, 1
            mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
            attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
            attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
        else:
            attn_mask = None

        self.register_buffer("attn_mask", attn_mask)
        self.fused_window_process = fused_window_process

    def forward(self, x):
        H, W = self.input_resolution
        B, L, C = x.shape
        assert L == H * W, "input feature has wrong size"

        shortcut = x
        x = self.norm1(x)
        x = x.view(B, H, W, C)

        # cyclic shift
        if self.shift_size > 0:
            if not self.fused_window_process:
                shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
                # partition windows
                x_windows = window_partition(shifted_x, self.window_size)  # nW*B, window_size, window_size, C
            else:
                x_windows = WindowProcess.apply(x, B, H, W, C, -self.shift_size, self.window_size)
        else:
            shifted_x = x
            # partition windows
            x_windows = window_partition(shifted_x, self.window_size)  # nW*B, window_size, window_size, C

        x_windows = x_windows.view(-1, self.window_size * self.window_size, C)  # nW*B, window_size*window_size, C

        # W-MSA/SW-MSA
        attn_windows = self.attn(x_windows, mask=self.attn_mask)  # nW*B, window_size*window_size, C

        # merge windows
        attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)

        # reverse cyclic shift
        if self.shift_size > 0:
            if not self.fused_window_process:
                shifted_x = window_reverse(attn_windows, self.window_size, H, W)  # B H' W' C
                x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
            else:
                x = WindowProcessReverse.apply(attn_windows, B, H, W, C, self.shift_size, self.window_size)
        else:
            shifted_x = window_reverse(attn_windows, self.window_size, H, W)  # B H' W' C
            x = shifted_x
        x = x.view(B, H * W, C)
        x = shortcut + self.drop_path(x)

        # FFN
        x = x + self.drop_path(self.mlp(self.norm2(x)))

        return x

    def extra_repr(self) -> str:
        return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \
               f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}"

    def flops(self):
        flops = 0
        H, W = self.input_resolution
        # norm1
        flops += self.dim * H * W
        # W-MSA/SW-MSA
        nW = H * W / self.window_size / self.window_size
        flops += nW * self.attn.flops(self.window_size * self.window_size)
        # mlp
        flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio
        # norm2
        flops += self.dim * H * W
        return flops
class SwinBlock(nn.Module):
    def __init__(self, outDim,input_resolution,winSize):
        super().__init__()
        self.SwinTransformerBlock = SwinTransformerBlock(dim=outDim,input_resolution=input_resolution,window_size=winSize)


    def forward(self, input):


        x=input
        # x = self.attnChannel1(input)
        B, C, H, W = x.shape
        #从B,C,H,W调整B,H,W,C
        x=x.permute(0,2,3,1)
        x=x.reshape(B,H*W,C)#BLC

        #第一次
        x=self.SwinTransformerBlock(x)


        x = x.reshape(B, H, W, C)  # BLC
        x = x.permute(0, 3,1, 2)
        return x
    #采用winsize/2的stride,winsize的maxpooling

class block(nn.Module):
    def __init__(self,inChannel,outChannel,kernel_size=3, padding=1,stride=1):
        super(block, self).__init__()
        self.conv = nn.Conv2d(inChannel, outChannel, kernel_size=kernel_size, padding=padding,stride=stride)
        self.bn = nn.BatchNorm2d(outChannel, momentum=0.1, affine=True)
        self.reLu = nn.ReLU(inplace=True)

    def forward(self, x):
        x=self.conv(x)
        x=self.bn(x)
        return self.reLu(x)
class ConvBNRelu(nn.Module):
    def __init__(self,inChannel,outChannel,kernel_size=3,padding=1,bias=False):
        super(ConvBNRelu, self).__init__()
        self.conv = nn.Conv2d(inChannel, outChannel, kernel_size=kernel_size, padding=padding,bias=bias)
        self.bn = nn.BatchNorm2d(outChannel, momentum=0.1, affine=True)
        self.reLu = nn.ReLU(inplace=True)

    def forward(self, x):
        x=self.conv(x)
        x=self.bn(x)
        return self.reLu(x)
class mlpooling(nn.Module):
    def __init__(self):
        super(mlpooling, self).__init__()
        self.pooling512=nn.MaxPool2d(512)

    def forward(self, x):
        pooling512=self.pooling512(x)
        pooling512=pooling512.repeat(1,1,512,512)
        # pooling512=F.interpolate(pooling512,512)


        return x+pooling512

class decoder(nn.Module):
    def __init__(self,depths=[32,32,32,32,32]):
        super(decoder, self).__init__()

        self.ConvTranspose1_0=nn.ConvTranspose2d(depths[1], depths[0], 2, 2)
        self.Conv1_0 = nn.Sequential(block(depths[0], depths[0]),
                                     block(depths[0], depths[0]))

        self.ConvTranspose2_1=nn.ConvTranspose2d(depths[2], depths[1], 2, 2)
        self.Conv2_1= nn.Sequential(block(depths[1]*2, depths[1]),
                                     block(depths[1], depths[1]))
        self.ConvTranspose2_0=nn.ConvTranspose2d(depths[1], depths[0], 2, 2)
        self.Conv2_0= nn.Sequential(block(depths[0], depths[0]),
                                     block(depths[0], depths[0]))

        self.ConvTranspose3_2=nn.ConvTranspose2d(depths[3], depths[2], 2, 2)
        self.Conv3_2= nn.Sequential(block(depths[2]*2, depths[2]),
                                     block(depths[2], depths[2]))
        self.ConvTranspose3_1=nn.ConvTranspose2d(depths[2], depths[1], 2, 2)
        self.Conv3_1= nn.Sequential(block(depths[1]*2, depths[1]),
                                     block(depths[1], depths[1]))
        self.ConvTranspose3_0=nn.ConvTranspose2d(depths[1], depths[0], 2, 2)
        self.Conv3_0= nn.Sequential(block(depths[0], depths[0]),
                                     block(depths[0], depths[0]))

        self.ConvTranspose4_3=nn.ConvTranspose2d(depths[4], depths[3], 2, 2)
        self.Conv4_3= nn.Sequential(block(depths[3]*2, depths[3]),
                                     block(depths[3], depths[3]))
        self.ConvTranspose4_2=nn.ConvTranspose2d(depths[3], depths[2], 2, 2)
        self.Conv4_2= nn.Sequential(block(depths[2]*2, depths[2]),
                                     block(depths[2], depths[2]))
        self.ConvTranspose4_1=nn.ConvTranspose2d(depths[2], depths[1], 2, 2)
        self.Conv4_1= nn.Sequential(block(depths[1]*2, depths[1]),
                                     block(depths[1], depths[1]))
        self.ConvTranspose4_0=nn.ConvTranspose2d(depths[1], depths[0], 2, 2)
        self.Conv4_0=nn.Sequential(block(depths[0], depths[0]),
                                     block(depths[0], depths[0]))

        self.ConvAll=nn.Sequential(block(depths[0]*5, depths[0]),
                                     block(depths[0], depths[0]))

    def forward(self,levels):
        level0 = levels[0]
        # level1的解码
        level1 = self.ConvTranspose1_0(levels[1])
        level1 = self.Conv1_0(level1)

        # level2的解码
        level2 = self.ConvTranspose2_1(levels[2])
        level2 = torch.cat([level2, levels[1]], dim=1)
        level2 = self.Conv2_1(level2)

        level2 = self.ConvTranspose2_0(level2)
        level2 = self.Conv2_0(level2)

        # level3的解码
        level3 = self.ConvTranspose3_2(levels[3])
        level3 = torch.cat([level3, levels[2]], dim=1)
        level3 = self.Conv3_2(level3)

        level3 = self.ConvTranspose3_1(level3)
        level3 = torch.cat([level3, levels[1]], dim=1)
        level3 = self.Conv3_1(level3)

        level3 = self.ConvTranspose3_0(level3)
        level3 = self.Conv3_0(level3)

        # level4的解码
        level4 = self.ConvTranspose4_3(levels[4])
        level4 = torch.cat([level4, levels[3]], dim=1)
        level4 = self.Conv4_3(level4)

        level4 = self.ConvTranspose4_2(level4)
        level4 = torch.cat([level4, levels[2]], dim=1)
        level4 = self.Conv4_2(level4)

        level4 = self.ConvTranspose4_1(level4)
        level4 = torch.cat([level4, levels[1]], dim=1)
        level4 = self.Conv4_1(level4)

        level4 = self.ConvTranspose4_0(level4)
        level4 = self.Conv4_0(level4)

        # 所有level的融合
        out = torch.cat([level0, level1, level2, level3,level4], dim=1)
        out = self.ConvAll(out)

        return out
class UNet_Decoder(nn.Module):
    def __init__(self,depths=[32,32,32,32,32]):
        super(UNet_Decoder, self).__init__()



        self.ConvTranspose4_3=nn.ConvTranspose2d(depths[4], depths[3], 2, 2)
        self.Conv4_3= nn.Sequential(block(depths[3]*2, depths[3]),
                                     block(depths[3], depths[3]))
        self.ConvTranspose4_2=nn.ConvTranspose2d(depths[3], depths[2], 2, 2)
        self.Conv4_2= nn.Sequential(block(depths[2]*2, depths[2]),
                                     block(depths[2], depths[2]))
        self.ConvTranspose4_1=nn.ConvTranspose2d(depths[2], depths[1], 2, 2)
        self.Conv4_1= nn.Sequential(block(depths[1]*2, depths[1]),
                                     block(depths[1], depths[1]))
        self.ConvTranspose4_0=nn.ConvTranspose2d(depths[1], depths[0], 2, 2)
        self.Conv4_0=nn.Sequential(block(depths[0], depths[0]),
                                     block(depths[0], depths[0]))

        self.ConvOut=nn.Sequential(block(depths[0], 2),
                                  )

    def forward(self,levels):

        # level4的解码
        level4 = self.ConvTranspose4_3(levels[4])
        level4 = torch.cat([level4, levels[3]], dim=1)
        level4 = self.Conv4_3(level4)

        level4 = self.ConvTranspose4_2(level4)
        level4 = torch.cat([level4, levels[2]], dim=1)
        level4 = self.Conv4_2(level4)

        level4 = self.ConvTranspose4_1(level4)
        level4 = torch.cat([level4, levels[1]], dim=1)
        level4 = self.Conv4_1(level4)

        level4 = self.ConvTranspose4_0(level4)
        level4 = self.Conv4_0(level4)

        # 所有level的融合
        # out = torch.cat([level0, level1, level2, level3,level4], dim=1)
        out = self.ConvOut(level4)

        return out
class patchNet(nn.Module):
    def __init__(self,inChannel,outChannel):
        super(patchNet, self).__init__()

        #将图像裁剪成不同的大小
        # self.resizeTo512 = transforms.Resize([512, 512])
        # self.resizeTo256=transforms.Resize([256,256])
        # self.resizeTo128 = transforms.Resize([128, 128])
        # self.resizeTo64 = transforms.Resize([64, 64])
        # self.resizeTo32 = transforms.Resize([32, 32])

        dim=32
        depths=[dim,dim*2,dim*4,dim*8,dim*16]

        # self.head=block(inChannel,depths[0])

        # self.backbone = nn.Sequential(
        #     block( 3, depths[0]),
        #     block( depths[0], depths[1]),
        #     block( depths[1], depths[2]),
        #     block( depths[2], depths[3]),
        #     block( depths[3], depths[4])
        # )
        self.CNNLayer1= nn.Sequential(
            block( 3, depths[0]),
            block( depths[0], depths[0])
        )
        self.CNNLayer2 = nn.Sequential(
            block(depths[0], depths[1]),
            block(depths[1], depths[1])
        )
        self.CNNLayer3 = nn.Sequential(
            block(depths[1], depths[2]),
            block(depths[2], depths[2])
        )
        self.CNNLayer4 = nn.Sequential(
            block(depths[2], depths[3]),
            block(depths[3], depths[3])
        )
        self.CNNLayer5 = nn.Sequential(
            block(depths[3], depths[4]),
            block(depths[4], depths[4])
        )
        self.layer1=LAttnBlock(8,3, depths[0])
        self.layer2 = LAttnBlock(8, depths[0], depths[1])
        self.layer3 = LAttnBlock(8, depths[1], depths[2])
        self.layer4 = LAttnBlock(8, depths[2], depths[3])
        self.layer5 = LAttnBlock(8, depths[3], depths[4])

        self.absolute_pos_embed512 = nn.Parameter(torch.zeros(1, 3, 512, 512))
        nn.init.trunc_normal_(self.absolute_pos_embed512, std=.02)
        #
        # self.absolute_pos_embed256 = nn.Parameter(torch.zeros(1, 3, 256, 256))
        # nn.init.trunc_normal_(self.absolute_pos_embed256, std=.02)
        #
        # self.absolute_pos_embed128 = nn.Parameter(torch.zeros(1, 3, 128, 128))
        # nn.init.trunc_normal_(self.absolute_pos_embed128, std=.02)
        #
        # self.absolute_pos_embed64 = nn.Parameter(torch.zeros(1, 3, 64, 64))
        # nn.init.trunc_normal_(self.absolute_pos_embed64, std=.02)
        #
        # self.absolute_pos_embed32 = nn.Parameter(torch.zeros(1, 3, 32, 32))
        # nn.init.trunc_normal_(self.absolute_pos_embed32, std=.02)

        #
        # self.backbone = nn.Sequential(block(64, 64),
        #                               block(64, 64),
        #                               block(64, 64),
        #                               block(64, 64),
        #                               block(64, 64),
        #                               block(64, 64),
        #                               block(64, 64),
        #
        #                               )
        #
        # self.transformer=nn.Sequential(LinearAttention(64),
        #                                LinearAttention(64),
        #                                LinearAttention(64),
        #                                LinearAttention(64),
        #                                LinearAttention(64),
        #                                LinearAttention(64),
        #                                LinearAttention(64),
        #                                )
        #输出层
        self.decoder=decoder(depths=depths)

        # self.From4to3 = nn.Conv2d(depths[4], depths[3], kernel_size=1, padding=0)
        # self.From4to2 = nn.Conv2d(depths[4], depths[2], kernel_size=1, padding=0)
        # self.From4to1 = nn.Conv2d(depths[4], depths[1], kernel_size=1, padding=0)
        # self.From4to0 = nn.Conv2d(depths[4], depths[0], kernel_size=1, padding=0)
        # self.convAll=block(64*6,64)

        #卷积成分类数
        # self.tail = nn.Conv2d(depths[0], outChannel, kernel_size=3, padding=1)

        # self.learn32=nn.Sequential(LearnAttention(1024),
        #                                LearnAttention(1024),
        #                                LearnAttention(1024),
        #                                LearnAttention(1024),
        #                                LearnAttention(1024),
        #                                LearnAttention(1024),
        #                                LearnAttention(1024),
        #                                )
        # self.learn64=nn.Sequential(LearnAttention(4096),
        #                                LearnAttention(4096),
        #                                LearnAttention(4096),
        #                                LearnAttention(4096),
        #                                LearnAttention(4096),
        #                                LearnAttention(4096),
        #                                LearnAttention(4096),
        #                                )
    def forward(self, input):





        # # Stage 1'
        # #x = F.relu(self.bn1(self.conv1(x)))
        # #对输入图片进行尺寸绽放
        #
        # patch512=x
        # patch256=self.resizeTo256(x)
        # patch128=self.resizeTo128(x)
        # patch64=self.resizeTo64(x)
        # patch32=self.resizeTo32(x)
        # # patch16 = self.resizeTo16(x)
        #
        # # 经过权重共享的backbone的encoder
        # # patch512=self.head(patch512)
        # # patch512=self.backbone(patch512)
        # # #stage1
        # levels=[patch512,patch256,patch128,patch64,patch32]
        # for i in [0,1,2,3,4]:
        #     # 卷积到32通道
        #     # levels[i]=self.head(levels[i])
        #
        #     #经过backbone
        #     levels[i]=self.backbone(levels[i])
        #     # levels[i],_ = self.transformer(levels[i])
        #     # levels[i]=self.resizeTo512(levels[i])
        #
        # levels[3]=self.From4to3(levels[3])
        # levels[2] = self.From4to2(levels[2])
        # levels[1] = self.From4to1(levels[1])
        # levels[0] = self.From4to0(levels[0])
        #局部特征提取
        locals=[]
        x=self.CNNLayer1(input)
        locals.append(x)
        x=F.max_pool2d(x,2,2)

        x = self.CNNLayer2(x)
        locals.append(x)
        x = F.max_pool2d(x, 2, 2)

        x = self.CNNLayer3(x)
        locals.append(x)
        x = F.max_pool2d(x, 2, 2)

        x = self.CNNLayer4(x)
        locals.append(x)
        x = F.max_pool2d(x, 2, 2)

        x = self.CNNLayer5(x)
        locals.append(x)

        #全局特征提取
        gs=[]
        x = input + self.absolute_pos_embed512
        x=self.layer1(x)
        gs.append(x)
        x=F.max_pool2d(x,2,2)
        x = self.layer2(x)
        gs.append(x)
        x = F.max_pool2d(x, 2, 2)
        x = self.layer3(x)
        gs.append(x)
        x = F.max_pool2d(x, 2, 2)
        x = self.layer4(x)
        gs.append(x)
        x = F.max_pool2d(x, 2, 2)
        x = self.layer5(x)
        gs.append(x)

        levels=locals+gs
        # x=levels[0]+levels[1]+levels[2]+levels[3]+levels[4]
        # # # x=self.convAll(torch.cat(levels,dim=1))
        #
        # out=self.tail(x)
        out= self.decoder(levels)
        return out
class patchNet1(nn.Module):
    def __init__(self,inChannel,outChannel):
        super(patchNet1, self).__init__()

        #将图像裁剪成不同的大小
        # self.resizeTo512 = transforms.Resize([512, 512])
        # self.resizeTo256=transforms.Resize([256,256])
        # self.resizeTo128 = transforms.Resize([128, 128])
        # self.resizeTo64 = transforms.Resize([64, 64])
        # self.resizeTo32 = transforms.Resize([32, 32])

        dim=32
        depths=[dim,dim*2,dim*4,dim*8,dim*16]

        # self.head=block(inChannel,depths[0])

        # self.backbone = nn.Sequential(
        #     block( 3, depths[0]),
        #     block( depths[0], depths[1]),
        #     block( depths[1], depths[2]),
        #     block( depths[2], depths[3]),
        #     block( depths[3], depths[4])
        # )
        # self.CNNLayer1= nn.Sequential(
        #     block( 3, depths[0]),
        #     block( depths[0], depths[0])
        # )
        # self.CNNLayer2 = nn.Sequential(
        #     block(depths[0], depths[1]),
        #     block(depths[1], depths[1])
        # )
        # self.CNNLayer3 = nn.Sequential(
        #     block(depths[1], depths[2]),
        #     block(depths[2], depths[2])
        # )
        # self.CNNLayer4 = nn.Sequential(
        #     block(depths[2], depths[3]),
        #     block(depths[3], depths[3])
        # )
        # self.CNNLayer5 = nn.Sequential(
        #     block(depths[3], depths[4]),
        #     block(depths[4], depths[4])
        # )
        self.layer1 = LAttnBlock(4,3,depths[0])
        self.layer2 = LAttnBlock(4, depths[0], depths[1])
        self.layer3 = LAttnBlock(4, depths[1], depths[2])
        self.layer4 = LAttnBlock(4, depths[2], depths[3])
        self.layer5 = LAttnBlock(4, depths[3], depths[4])

        self.absolute_pos_embed512 = nn.Parameter(torch.zeros(1, 3, 512, 512))
        nn.init.trunc_normal_(self.absolute_pos_embed512, std=.02)

        #
        # self.absolute_pos_embed256 = nn.Parameter(torch.zeros(1, 3, 256, 256))
        # nn.init.trunc_normal_(self.absolute_pos_embed256, std=.02)
        #
        # self.absolute_pos_embed128 = nn.Parameter(torch.zeros(1, 3, 128, 128))
        # nn.init.trunc_normal_(self.absolute_pos_embed128, std=.02)
        #
        # self.absolute_pos_embed64 = nn.Parameter(torch.zeros(1, 3, 64, 64))
        # nn.init.trunc_normal_(self.absolute_pos_embed64, std=.02)
        #
        # self.absolute_pos_embed32 = nn.Parameter(torch.zeros(1, 3, 32, 32))
        # nn.init.trunc_normal_(self.absolute_pos_embed32, std=.02)

        #
        # self.backbone = nn.Sequential(block(64, 64),
        #                               block(64, 64),
        #                               block(64, 64),
        #                               block(64, 64),
        #                               block(64, 64),
        #                               block(64, 64),
        #                               block(64, 64),
        #
        #                               )
        #
        # self.transformer=nn.Sequential(LinearAttention(64),
        #                                LinearAttention(64),
        #                                LinearAttention(64),
        #                                LinearAttention(64),
        #                                LinearAttention(64),
        #                                LinearAttention(64),
        #                                LinearAttention(64),
        #                                )
        #输出层
        self.decoder=decoder(depths=depths)

        # self.From4to3 = nn.Conv2d(depths[4], depths[3], kernel_size=1, padding=0)
        # self.From4to2 = nn.Conv2d(depths[4], depths[2], kernel_size=1, padding=0)
        # self.From4to1 = nn.Conv2d(depths[4], depths[1], kernel_size=1, padding=0)
        # self.From4to0 = nn.Conv2d(depths[4], depths[0], kernel_size=1, padding=0)
        # self.convAll=block(64*6,64)

        #卷积成分类数
        # self.tail = nn.Conv2d(depths[0], outChannel, kernel_size=3, padding=1)

        # self.learn32=nn.Sequential(LearnAttention(1024),
        #                                LearnAttention(1024),
        #                                LearnAttention(1024),
        #                                LearnAttention(1024),
        #                                LearnAttention(1024),
        #                                LearnAttention(1024),
        #                                LearnAttention(1024),
        #                                )
        # self.learn64=nn.Sequential(LearnAttention(4096),
        #                                LearnAttention(4096),
        #                                LearnAttention(4096),
        #                                LearnAttention(4096),
        #                                LearnAttention(4096),
        #                                LearnAttention(4096),
        #                                LearnAttention(4096),
        #                                )
    def forward(self, input):

        #全局特征提取
        gs=[]
        x = input + self.absolute_pos_embed512
        x=self.layer1(x)
        # x = self.layer1_2(x)
        # x = self.CNNLayer1(x)
        gs.append(x)

        x=F.max_pool2d(x,2,2)
        x = self.layer2(x)
        # x = self.layer2_2(x)
        # x = self.CNNLayer2(x)
        gs.append(x)

        x = F.max_pool2d(x, 2, 2)
        x = self.layer3(x)
        # x = self.layer3_2(x)
        # x = self.CNNLayer3(x)
        gs.append(x)

        x = F.max_pool2d(x, 2, 2)
        x = self.layer4(x)
        # x = self.layer4_2(x)
        # x = self.CNNLayer4(x)
        gs.append(x)

        x = F.max_pool2d(x, 2, 2)
        x = self.layer5(x)
        # x = self.layer5_2(x)
        # x = self.CNNLayer5(x)
        gs.append(x)


        # x=levels[0]+levels[1]+levels[2]+levels[3]+levels[4]
        # # # x=self.convAll(torch.cat(levels,dim=1))
        #
        # out=self.tail(x)
        out= self.decoder(gs)
        return out
class patchNet2(nn.Module):
    def __init__(self,inChannel,outChannel):
        super(patchNet2, self).__init__()

        dim=32
        depths=[dim,dim*2,dim*4,dim*2,dim]

        self.CNNLayer1= nn.Sequential(
            block( 3, depths[0]),
            block( depths[0], depths[0])
        )
        self.CNNLayer2 = nn.Sequential(
            block(depths[0], depths[0]),
            block(depths[0], depths[0])
        )
        self.CNNLayer3 = nn.Sequential(
            block(depths[0], depths[1]),
            block(depths[1], depths[1])
        )
        self.CNNLayer4 = nn.Sequential(
            block(depths[1], depths[1]),
            block(depths[1], depths[1])
        )
        self.CNNLayer5 = nn.Sequential(
            block(depths[1], depths[2]),
            block(depths[2], depths[2])
        )
        self.CNNLayer6 = nn.Sequential(
            block(depths[2], depths[3]),
            block(depths[3], depths[3])
        )
        self.CNNLayer7 = nn.Sequential(
            block(depths[3], depths[3]),
            block(depths[3], depths[3])
        )
        self.CNNLayer8 = nn.Sequential(
            block(depths[3], depths[4]),
            block(depths[4], depths[4])
        )
        self.CNNLayer9 = nn.Sequential(
            block(depths[4], depths[4]),
            block(depths[4], depths[4])
        )

        self.decoder=decoder(depths=depths)
        self.out=nn.Conv2d(depths[4],2,kernel_size=1,padding=0)
    def layer(self,cnnlayer,x):
        x256 = x
        x128 = F.interpolate(x, size=(128, 128))
        x64 = F.interpolate(x, size=(64, 64))
        x32 = F.interpolate(x, size=(32, 32))
        x16 = F.interpolate(x, size=(16, 16))
        layer = [x16, x32, x64, x128, x256]
        layer = [cnnlayer(p) for p in layer]
        layer = [F.interpolate(p, size=(256, 256)) for p in layer]
        layer = layer[0]+layer[1]+layer[2]+layer[3]+layer[4]
        return layer

    def forward(self, x):


        # #局部特征提取
        # layer1 = self.layer(self.CNNLayer1,x)
        # layer2 = self.layer(self.CNNLayer2, layer1)
        # layer3 = self.layer(self.CNNLayer3, layer2)
        # layer4 = self.layer(self.CNNLayer4, layer3)
        # layer5 = self.layer(self.CNNLayer5, layer4)
        # layer6 = self.layer(self.CNNLayer6, layer5)
        # layer7 = self.layer(self.CNNLayer7, layer6)
        # layer8 = self.layer(self.CNNLayer8, layer7)
        # layer9 = self.layer(self.CNNLayer9, layer8)
        out=self.out(layer9)

        return out


class patchNet3(nn.Module):
    def __init__(self, inChannel, outChannel):
        super(patchNet3, self).__init__()

        dim = 16
        depths = [dim, dim * 2, dim * 4, dim * 8, dim*16]
        self.backbone=nn.Sequential(
            block(3, depths[0]),
            block(depths[0], depths[0]),
            block(depths[0], depths[1]),
            block(depths[1], depths[1]),
            block(depths[1], depths[2]),
            block(depths[2], depths[2]),
            block(depths[2], depths[3]),
            block(depths[3], depths[3]),
            block(depths[3], depths[4]),
            block(depths[4], depths[4])

        )
        self.CNNLayer3 = nn.Sequential(
            block(depths[4], depths[3]),

        )
        self.CNNLayer2 = nn.Sequential(
            block(depths[4], depths[2]),

        )
        self.CNNLayer1 = nn.Sequential(
            block(depths[4], depths[1]),

        )
        self.CNNLayer0 = nn.Sequential(
            block(depths[4], depths[0]),

        )


        self.decoder = decoder(depths=depths)
        self.out = nn.Conv2d(depths[0], 2, kernel_size=1, padding=0)



    def forward(self, x):
        x256=x
        x128=F.interpolate(x,size=(128,128))
        x64=F.interpolate(x,size=(64,64))
        x32=F.interpolate(x,size=(32,32))
        x16=F.interpolate(x,size=(16,16))

        x256=self.backbone(x256)
        x128 = self.backbone(x128)
        x64 = self.backbone(x64)
        x32 = self.backbone(x32)
        x16 = self.backbone(x16)


        x256=self.CNNLayer0(x256)
        x128 = self.CNNLayer1(x128)
        x64 = self.CNNLayer2(x64)
        x32 = self.CNNLayer3(x32)

        x = [x256, x128, x64, x32, x16]
        x=self.decoder(x)
        out=self.out(x)

        return out
class pool_block(nn.Module):
    def __init__(self,inDepth,inH,inW,pool_factor, outDepth=32 ):
        super().__init__()
        self.inH=inH
        self.inW=inW
        pool_size = strides = [inH // pool_factor,inW // pool_factor]

        self.outDepth=outDepth
        self.AvgPool2d=nn.AvgPool2d(pool_size, strides)
        self.ConvBNRelu=ConvBNRelu(inDepth,outDepth,kernel_size=1,bias=False)
        # self.Upsample=nn.Upsample([inH,inW], mode='nearest')
    def forward(self, feats):
        x = self.AvgPool2d(feats)
        x = self.ConvBNRelu(x)
        x = F.upsample_bilinear(x,[self.inH,self.inW])
        return x
class Learn_Unet(nn.Module):
    def __init__(self):
        super(Learn_Unet,self).__init__()
        dim = 32
        depths = [dim, dim * 2, dim * 4, dim * 8, dim * 16]

        self.Down1 = nn.Sequential(
                                    SwinBlock(8,3,depths[0],(512,512))
                                    # LAttnBlock3(8,depths[0],depths[0]),
                                    )

        self.Down2 = nn.Sequential(
                                    SwinBlock(8,depths[0],depths[1],(256,256)),
                                    # LAttnBlock3(8,depths[1],depths[1]),
                                   )
        self.Down3 = nn.Sequential(
                                    SwinBlock(8,depths[1],depths[2],(128,128)),
                                    # LAttnBlock3(8,depths[2],depths[2]),
                                   )
        self.Down4 = nn.Sequential(
                                    SwinBlock(8,depths[2],depths[3],(64,64)),
                                    # LAttnBlock3(8,depths[3],depths[3]),
                                    )
        self.Down5 = nn.Sequential(
                                    SwinBlock(8,depths[3],depths[4],(32,32)),
                                    # LAttnBlock3(8,depths[4],depths[4]),
                                    )

        # self.Up4 = nn.Sequential(nn.Upsample(scale_factor=2),
        #                             LAttnBlock3(8,depths[4],depths[3]),
        #                             LAttnBlock3(8,depths[3],depths[3]),
        #                             )
        # self.Up4_1 = nn.Sequential(
        #                          LAttnBlock3(8, depths[4], depths[3]),
        #                          LAttnBlock3(8, depths[3], depths[3]),
        #                          )
        #
        # self.Up3 = nn.Sequential(nn.Upsample(scale_factor=2),
        #                             LAttnBlock3(8,depths[3],depths[2]),
        #                             LAttnBlock3(8,depths[2],depths[2]),
        #                             )
        # self.Up3_1 = nn.Sequential(
        #                          LAttnBlock3(8, depths[3], depths[2]),
        #                          LAttnBlock3(8, depths[2], depths[2]),
        #                          )
        #
        # self.Up2 = nn.Sequential(nn.Upsample(scale_factor=2),
        #                             LAttnBlock3(8,depths[2],depths[1]),
        #                             LAttnBlock3(8,depths[1],depths[1]),
        #                             )
        # self.Up2_1 = nn.Sequential(
        #                          LAttnBlock3(8, depths[2], depths[1]),
        #                          LAttnBlock3(8, depths[1], depths[1]),
        #                          )
        # self.Up1 = nn.Sequential(nn.Upsample(scale_factor=2),
        #                             LAttnBlock3(8,depths[1],depths[0]),
        #                             LAttnBlock3(8,depths[0],depths[0]),
        #                             )
        # self.Up1_1 = nn.Sequential(
        #                          LAttnBlock3(8, depths[1], depths[0]),
        #                          LAttnBlock3(8, depths[0], depths[0]),
        #                          )

        # self.CNN1 = nn.Sequential(
        #     block(3, depths[0]),
        #     block(depths[0],depths[0])
        # )
        # self.CNN2 = nn.Sequential(
        #     block(depths[0], depths[1]),
        #     block(depths[1], depths[1])
        # )
        # self.CNN3 = nn.Sequential(
        #     block(depths[1], depths[2]),
        #     block(depths[2], depths[2])
        # )
        # self.CNN4 = nn.Sequential(
        #     block(depths[2], depths[3]),
        #     block(depths[3], depths[3])
        # )
        # self.CNN5 = nn.Sequential(
        #     block(depths[3], depths[4]),
        #     block(depths[4], depths[4])
        # )

        # self.Conv4 = nn.Conv2d(depths[0], 2, 1, bias=True)

        self.UNet_Decoder = UNet_Decoder(depths)
    def forward(self, input):
        #卷积
        # c1=x=self.CNN1(input)
        # x = F.max_pool2d(x, 2, 2)
        #
        # c2 = x = self.CNN2(x)
        # x = F.max_pool2d(x, 2, 2)
        #
        # c3 = x = self.CNN3(x)
        # x = F.max_pool2d(x, 2, 2)
        #
        # c4 = x = self.CNN4(x)
        # x = F.max_pool2d(x, 2, 2)
        #
        # c5 = x = self.CNN5(x)

        #selfattion
        # x = x + self.absolute_pos_embed512
        d1=x = self.Down1(input)
        # x = self.layer1_2(x)
        # x = self.CNNLayer1(x)


        x = F.max_pool2d(x, 2, 2)
        d2=x = self.Down2(x)
        # x = self.layer2_2(x)
        # x = self.CNNLayer2(x)


        x = F.max_pool2d(x, 2, 2)
        d3=x = self.Down3(x)
        # x = self.layer3_2(x)
        # x = self.CNNLayer3(x)


        x = F.max_pool2d(x, 2, 2)
        d4=x = self.Down4(x)
        # x = self.layer4_2(x)
        # x = self.CNNLayer4(x)


        x = F.max_pool2d(x, 2, 2)
        d5=x = self.Down5(x)


        # # 合并CNN和selfattion
        # d1 = d1 + c1
        # d2 = d2 + c2
        # d3 = d3 + c3
        # d4 = d4 + c4
        # d5 = d5 + c5

        #解码
        # x=self.Up4(x)
        #
        # x=torch.cat([x,d4],dim=1)
        # x=self.Up4_1(x)
        #
        # x = self.Up3(x)
        # x = torch.cat([x, d3], dim=1)
        # x = self.Up3_1(x)
        #
        # x = self.Up2(x)
        # x = torch.cat([x, d2], dim=1)
        # x = self.Up2_1(x)
        #
        # x = self.Up1(x)
        # x = torch.cat([x, d1], dim=1)
        # x = self.Up1_1(x)
        #
        # x = self.Conv4(x)


        return self.UNet_Decoder([d1,d2,d3,d4,d5])

#buildformer
class ConvBN(nn.Sequential):
    def __init__(self, in_channels, out_channels, kernel_size=3, dilation=1, stride=1, norm_layer=nn.BatchNorm2d, bias=False):
        super(ConvBN, self).__init__(
            nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, bias=bias,
                      dilation=dilation, stride=stride, padding=((stride - 1) + dilation * (kernel_size - 1)) // 2),
            norm_layer(out_channels)
        )
class Conv(nn.Sequential):
    def __init__(self, in_channels, out_channels, kernel_size=3, dilation=1, stride=1, bias=False):
        super(Conv, self).__init__(
            nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, bias=bias,
                      dilation=dilation, stride=stride, padding=((stride - 1) + dilation * (kernel_size - 1)) // 2)
        )
class LWMSA(nn.Module):
    def __init__(self,
                 dim=16,
                 num_heads=8,
                 window_size=16,
                 qkv_bias=False
                 ):
        super().__init__()
        self.num_heads = num_heads
        self.eps = 1e-6
        self.ws = window_size

        self.qkv = Conv(dim, dim*3, kernel_size=1, bias=qkv_bias)
        self.proj = ConvBN(dim, dim, kernel_size=1)

    def pad(self, x, ps):
        _, _, H, W = x.size()
        if W % ps != 0:
            x = F.pad(x, (0, ps - W % ps))
        if H % ps != 0:
            x = F.pad(x, (0, 0, 0, ps - H % ps))
        return x

    def l2_norm(self, x):
        return torch.einsum("bhcn, bhn->bhcn", x, 1 / torch.norm(x, p=2, dim=-2))

    def forward(self, x):
        _, _, H, W = x.shape
        x = self.pad(x, self.ws)

        B, C, Hp, Wp = x.shape
        hh, ww = Hp//self.ws, Wp//self.ws
        # print(x.shape)
        qkv = self.qkv(x)

        q, k, v = rearrange(qkv, 'b (qkv h d) (hh ws1) (ww ws2) -> qkv (b hh ww) h d (ws1 ws2)',
                            b=B, h=self.num_heads, d=C//self.num_heads, qkv=3, ws1=self.ws, ws2=self.ws)

        q = self.l2_norm(q).permute(0, 1, 3, 2)
        k = self.l2_norm(k)
        # print(q.shape, v.shape, k.shape)

        tailor_sum = 1 / (self.ws * self.ws + torch.einsum("bhnc, bhc->bhn", q, torch.sum(k, dim=-1) + self.eps))
        # print(tailor_sum.shape)
        attn = torch.einsum('bhmn, bhcn->bhmc', k, v)
        # print(q.shape, attn.shape)
        attn = torch.einsum("bhnm, bhmc->bhcn", q, attn)
        # print(attn.shape)
        v = torch.einsum("bhcn->bhc", v).unsqueeze(-1)
        v = v.expand(B*hh*ww, self.num_heads, C//self.num_heads,  self.ws * self.ws)
        attn = attn + v
        attn = torch.einsum("bhcn, bhn->bhcn", attn, tailor_sum)
        attn = rearrange(attn, '(b hh ww) h d (ws1 ws2) -> b (h d) (hh ws1) (ww ws2)',
                         b=B, h=self.num_heads, d=C // self.num_heads, ws1=self.ws, ws2=self.ws,
                         hh=Hp // self.ws, ww=Wp // self.ws)
        attn = attn[:, :, :H, :W]

        return attn

#linformer
import math

def default(val, default_val):
    return val if val is not None else default_val

def init_(tensor):
    dim = tensor.shape[-1]
    std = 1 / math.sqrt(dim)
    tensor.uniform_(-std, std)
    return tensor
class PatchMerging(nn.Module):
    r""" Patch Merging Layer.

    Args:
        input_resolution (tuple[int]): Resolution of input feature.
        dim (int): Number of input channels.
        norm_layer (nn.Module, optional): Normalization layer.  Default: nn.LayerNorm
    """

    def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
        super().__init__()
        self.input_resolution = input_resolution
        self.dim = dim
        self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
        self.norm = norm_layer(4 * dim)

    def forward(self, x):
        """
        x: B, H*W, C
        """
        H, W = self.input_resolution
        B, L, C = x.shape
        assert L == H * W, "input feature has wrong size"
        assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even."

        x = x.view(B, H, W, C)

        x0 = x[:, 0::2, 0::2, :]  # B H/2 W/2 C
        x1 = x[:, 1::2, 0::2, :]  # B H/2 W/2 C
        x2 = x[:, 0::2, 1::2, :]  # B H/2 W/2 C
        x3 = x[:, 1::2, 1::2, :]  # B H/2 W/2 C
        x = torch.cat([x0, x1, x2, x3], -1)  # B H/2 W/2 4*C
        x = x.view(B, -1, 4 * C)  # B H/2*W/2 4*C

        x = self.norm(x)
        x = self.reduction(x)

        return x

    def extra_repr(self) -> str:
        return f"input_resolution={self.input_resolution}, dim={self.dim}"

    def flops(self):
        H, W = self.input_resolution
        flops = H * W * self.dim
        flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim
        return flops
class LinformerSelfAttention(nn.Module):
    def __init__(self, dim, seq_len, k = 256, heads = 2, dim_head = None, one_kv_head = False, share_kv = False, dropout = 0.):
        super().__init__()
        assert (dim % heads) == 0, 'dimension must be divisible by the number of heads'

        self.seq_len = seq_len
        self.k = k

        self.heads = heads

        dim_head = default(dim_head, dim // heads)
        self.dim_head = dim_head

        self.to_q = nn.Linear(dim, dim_head * heads, bias = False)

        kv_dim = dim_head if one_kv_head else (dim_head * heads)
        self.to_k = nn.Linear(dim, kv_dim, bias = False)
        self.proj_k = nn.Parameter(init_(torch.zeros(seq_len, k)))

        self.share_kv = share_kv
        if not share_kv:
            self.to_v = nn.Linear(dim, kv_dim, bias = False)
            self.proj_v = nn.Parameter(init_(torch.zeros(seq_len, k)))

        self.dropout = nn.Dropout(dropout)
        self.to_out = nn.Linear(dim_head * heads, dim)

    def forward(self, x, context = None, **kwargs):
        b, n, d, d_h, h, k = *x.shape, self.dim_head, self.heads, self.k

        kv_len = n if context is None else context.shape[1]
        assert kv_len == self.seq_len, f'the sequence length of the key / values must be {self.seq_len} - {kv_len} given'

        queries = self.to_q(x)

        proj_seq_len = lambda args: torch.einsum('bnd,nk->bkd', *args)

        kv_input = x if context is None else context

        keys = self.to_k(kv_input)
        values = self.to_v(kv_input) if not self.share_kv else keys

        kv_projs = (self.proj_k, self.proj_v if not self.share_kv else self.proj_k)

        # project keys and values along the sequence length dimension to k

        keys, values = map(proj_seq_len, zip((keys, values), kv_projs))

        # merge head into batch for queries and key / values

        queries = queries.reshape(b, n, h, -1).transpose(1, 2)

        merge_key_values = lambda t: t.reshape(b, k, -1, d_h).transpose(1, 2).expand(-1, h, -1, -1)
        keys, values = map(merge_key_values, (keys, values))

        # attention

        dots = torch.einsum('bhnd,bhkd->bhnk', queries, keys) * (d_h ** -0.5)
        attn = dots.softmax(dim=-1)
        attn = self.dropout(attn)
        out = torch.einsum('bhnk,bhkd->bhnd', attn, values)

        # split heads
        out = out.transpose(1, 2).reshape(b, n, -1)
        return self.to_out(out)
class LinformerBlock(nn.Module):
    def __init__(self,dim,L,winSize=8):
        super(LinformerBlock, self).__init__()

        self.linformer = LinformerSelfAttention(dim,L)
        self.winSize=winSize
    def forward(self, x):
        N, C, H, W = x.shape
        x = learnwindow_partition(x, self.winSize)
        N,C,winH,winW=x.shape
        x=x.reshape(N,C,winH*winW)
        x = x.permute(0, 2, 1)
        x=self.linformer(x)
        x = x.permute(0, 2, 1)
        x = x.reshape(N, C, winH , winW)
        x=learnwindow_reverse(x,H,W)
        return x
#多尺度UTNet的transformer
class MTNet(nn.Module):
    def __init__(self):
        super(MTNet, self).__init__()
        dim=32
        depths=[dim,dim*2,dim*4,dim*8,dim*16]

        self.CNNLayer1= nn.Sequential(
            block( 3, depths[0]),
            block(depths[0], depths[0]),
        )
        self.CNNLayer2 = nn.Sequential(
            block(depths[0], depths[1]),
            block(depths[1], depths[1]),
        )
        self.CNNLayer3 = nn.Sequential(
            block(depths[1], depths[2]),
            block(depths[2], depths[2]),
        )
        self.CNNLayer4 = nn.Sequential(
            block(depths[2], depths[3]),
            block(depths[3], depths[3]),
        )
        self.CNNLayer5 = nn.Sequential(
            block(depths[3], depths[4]),
            block(depths[4], depths[4]),
        )

        #transformer
        # self.layer2 = LinformerBlock(depths[1],256*256)
        # self.layer3 = LinformerBlock(depths[2],128*128)
        self.layer4 = LinformerBlock(depths[3],64*64)
        self.layer5 = LinformerBlock(depths[4],32*32)



        #输出层
        self.decoder=decoder(depths=depths)
        self.head=nn.Conv2d(3, depths[3], kernel_size=1, padding=0)

        self.head1 = nn.Conv2d(depths[3], depths[4], kernel_size=1, padding=0)

    def forward(self, input):

        #局部特征提取
        locals=[]
        x=self.CNNLayer1(input)
        locals.append(x)
        x=F.max_pool2d(x,2,2)

        x = self.CNNLayer2(x)
        locals.append(x)
        x = F.max_pool2d(x, 2, 2)

        x = self.CNNLayer3(x)
        locals.append(x)
        # x = F.max_pool2d(x, 2, 2)

        # x = self.CNNLayer4(x)
        # locals.append(x)
        # x = F.max_pool2d(x, 2, 2)
        #
        # x = self.CNNLayer5(x)
        # locals.append(x)

        #全局特征提取
        # gs=[]
        # x=self.head(input)
        # gs.append(x)
        # x = F.max_pool2d(x, 2, 2)
        #
        # x=self.layer1(x)
        # gs.append(x)
        # x=F.max_pool2d(x,2,2)
        #
        # x = self.layer2(x)
        # gs.append(x)
        # x = F.max_pool2d(x, 2, 2)
        #
        # x = self.layer3(x)
        # gs.append(x)
        # x = F.max_pool2d(x, 2, 2)
        #
        # x = self.layer4(x)
        # gs.append(x)

        x=F.interpolate(input,size=(64,64),mode="nearest")
        x=self.head(x)

        x = self.layer4(x)
        locals.append(x)
        x = F.max_pool2d(x, 2, 2)

        x = self.head1(x)
        x = self.layer5(x)
        locals.append(x)


        out=self.decoder(locals)
        # x=F.upsample_nearest(x,scale_factor=16)

        # out=self.out(x)
        return out

class MTNet1(nn.Module):
    def __init__(self):
        super(MTNet1, self).__init__()
        dim = 32
        depths = [dim, dim , dim , dim , dim ]

        self.CNNLayer = nn.Sequential(
            block(3, depths[0]),
            block(depths[0], depths[0]),
            block(depths[0], depths[0]),
            block(depths[0], depths[0]),
            block(depths[0], depths[0]),
            block(depths[0], depths[0]),
        )

        # self.CNNLayer1 = nn.Sequential(
        #     block(3, depths[0]),
        #     block(depths[0], depths[0]),
        #     block(depths[0], depths[0]),
        #     block(depths[0], depths[0]),
        #     block(depths[0], depths[0]),
        #     block(depths[0], depths[0]),
        # )


        # self.Transformerlayer128= nn.Sequential(
        #     nn.Conv2d(3, depths[0], kernel_size=1, padding=0),
        #     LinformerBlock(depths[0], 128 * 128),
        #     LinformerBlock(depths[0], 128 * 128),
        #
        # )
        # self.Transformerlayer64 = nn.Sequential(
        #
        #     LinformerBlock(depths[0], 64 * 64),
        #     LinformerBlock(depths[0], 64 * 64),
        # )
        # self.Transformerlayer32 = nn.Sequential(
        #
        #     LinformerBlock(depths[0], 32 * 32),
        #     LinformerBlock(depths[0], 32 * 32),
        # )

        # self.transformerLayer16=nn.Sequential(
        #     # block(3, depths[0]),
        #     LinearAttention(depths[0],4,depths[0]//4,reduce_size=16),
        #     # LinearAttention(depths[0], 4, depths[0] // 4, reduce_size=16)
        # )
        self.transformerLayer16 = LinearAttention(depths[0], 4, depths[0] // 4, reduce_size=16)
        self.transformerLayer8 = LinearAttention(depths[0], 4, depths[0] // 4, reduce_size=8)
        self.transformerLayer4 = LinearAttention(depths[0], 4, depths[0] // 4, reduce_size=4)

        self.head = nn.Conv2d(3, depths[0], kernel_size=1, padding=0)
        self.Tail=nn.Conv2d(depths[0], 2, kernel_size=1, padding=0)
        self.decoder=decoder(depths)


    def forward(self, input):
        # 局部特征提取

        local0 = self.CNNLayer(input)

        x = F.interpolate(input, size=(256, 256), mode="nearest")
        local1=self.CNNLayer(x)


        x = F.interpolate(input, size=(128, 128), mode="nearest")
        local2 = self.CNNLayer(x)

        x = F.interpolate(input, size=(64, 64), mode="nearest")
        local3 = self.CNNLayer(x)

        x = F.interpolate(input, size=(32, 32), mode="nearest")
        local4 = self.CNNLayer(x)

###############################
        # x=F.interpolate(input,size=(128,128),mode="nearest")
        # gs2=self.Transformerlayer128(x)
        #
        # x = F.interpolate(gs2, size=(64, 64), mode="nearest")
        # gs3 = self.Transformerlayer64(x)
        #
        # x = F.interpolate(gs3, size=(32, 32), mode="nearest")
        # gs4 = self.Transformerlayer32(x)

        x=F.interpolate(input, size=(128, 128), mode="nearest")
        x=self.head(x)
        gs16=self.transformerLayer16(x)
        gs16=F.interpolate(gs16, size=(512, 512), mode="nearest")

        gs8 = self.transformerLayer8(x)
        gs8=F.interpolate(gs8, size=(512, 512), mode="nearest")

        gs4 = self.transformerLayer4(x)
        gs4=F.interpolate(gs4, size=(512, 512), mode="nearest")


        out=self.decoder([local0+gs16+gs8+gs4,local1,local2,local3,local4])



        return out

class MTNet2(nn.Module):
    def __init__(self):
        super(MTNet2, self).__init__()
        dim = 32
        depths = [dim, dim , dim , dim , dim ]
        self.head=block(3, depths[0],kernel_size=3,padding=1)
        self.CNNLayer1 = nn.Sequential(

            block(depths[0], depths[0], kernel_size=3, padding=1),

            block(depths[0], depths[0], kernel_size=3, padding=1),

        )
        self.CNNLayer2 = nn.Sequential(
            block(depths[0], depths[1], kernel_size=3, padding=1),
            block(depths[1], depths[1], kernel_size=3, padding=1)
        )
        self.CNNLayer3 = nn.Sequential(
            block(depths[1], depths[2],kernel_size=3,padding=1),
            block(depths[2], depths[2], kernel_size=3, padding=1)
        )
        self.CNNLayer4 = nn.Sequential(
            block(depths[2], depths[3],kernel_size=3,padding=1),
            block(depths[3], depths[3], kernel_size=3, padding=1)
        )
        self.CNNLayer5 = nn.Sequential(
            block(depths[3], depths[4],kernel_size=3,padding=1),
            block(depths[4], depths[4], kernel_size=3, padding=1)
        )


        # self.patchMerge2=PatchMerging((512,512),depths[0])

        # self.TransLayer2 =nn.Sequential(
        #     nn.Conv2d(3, depths[0], kernel_size=1, padding=0),
        #     LinformerBlock(depths[1],256*256,winSize=256),
        #     LinformerBlock(depths[1],256*256,winSize=256)
        # )
        # self.head=block(3, depths[0],kernel_size=1,padding=0)
        # # self.transformerLayer64 = LinearAttention(depths[0], 4, depths[0] // 4, reduce_size=64)
        # # self.transformerLayer32 = LinearAttention(depths[0], 4, depths[0] // 4, reduce_size=32)
        # self.transformerLayer16 = nn.Sequential(
        #     LinearAttention(depths[0], 4, depths[0], reduce_size=16),
        #     LinearAttention(depths[0], 4, depths[0], reduce_size=16),
        #
        #     LinearAttention(depths[0], 4, depths[0], reduce_size=16),
        #
        #     LinearAttention(depths[0], 4, depths[0], reduce_size=16),
        # )
            # self.transformerLayer8 = LinearAttention(depths[0], 4, depths[0] // 4, reduce_size=8)
        # self.transformerLayer4 = LinearAttention(depths[0], 4, depths[0] // 4, reduce_size=4)

        self.UNet_Decoder=UNet_Decoder(depths)


    def forward(self, input):
        # 局部特征提取
        # locals=[]
        # x = self.CNNLayer1(input)
        # locals.append(x)
        #
        # x = F.max_pool2d(x,2)
        # x = self.CNNLayer2(x)
        # locals.append(x)
        #
        # x = F.max_pool2d(x,2)
        # x = self.CNNLayer3(x)
        # locals.append(x)
        #
        # x = F.max_pool2d(x,2)
        # x = self.CNNLayer4(x)
        # locals.append(x)
        #
        # x = F.max_pool2d(x,2)
        # x = self.CNNLayer5(x)
        # locals.append(x)

###############################
        # x=F.interpolate(input,size=(128,128),mode="nearest")
        # gs2=self.Transformerlayer128(x)
        #
        # x = F.interpolate(gs2, size=(64, 64), mode="nearest")
        # gs3 = self.Transformerlayer64(x)
        #
        # x = F.interpolate(gs3, size=(32, 32), mode="nearest")
        # gs4 = self.Transformerlayer32(x)
        gs=[]
        x=self.head(input)
        x = self.CNNLayer1(x)
        x = self.CNNLayer1(x)
        x = self.CNNLayer1(x)
        gs.append(x)

        x=F.max_pool2d(x,2)
        x=self.CNNLayer2(x)
        x = self.CNNLayer2(x)
        x = self.CNNLayer2(x)
        gs.append(x)

        x=F.max_pool2d(x,2)
        x = self.CNNLayer3(x)
        x = self.CNNLayer3(x)
        x = self.CNNLayer3(x)
        gs.append(x)

        x=F.max_pool2d(x,2)
        x = self.CNNLayer4(x)
        x = self.CNNLayer4(x)
        x = self.CNNLayer4(x)
        gs.append(x)

        x=F.max_pool2d(x,2)
        x = self.CNNLayer5(x)
        x = self.CNNLayer5(x)
        x = self.CNNLayer5(x)
        gs.append(x)

##############################
        # x = F.interpolate(input, size=(128, 128))
        # x=self.head(x)
        # gs128=self.transformerLayer16(x)
        #
        # x = F.interpolate(input, size=(64, 64))
        # x = self.head(x)
        # gs64 = self.transformerLayer16(x)
        # # gs32=self.transformerLayer32(x)
        # # gs64=self.transformerLayer64(x)
        #
        # ####################
        # gs[2]=gs[2]+gs128#+gs32+gs64
        # gs[3] = gs[3] + gs64
        out=self.UNet_Decoder(gs)



        return out